package com.yksj.healthtalk.ui.home;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import org.handmark.pulltorefresh.library.PullToRefreshScrollView;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog.OnDilaogClickListener;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.comm.SingleBtnFragmentDialog;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.entity.TickMesg;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonsfHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.doctor.DoctorServiceActivity;
import com.yksj.healthtalk.ui.views.ServiceTypeView;
import com.yksj.healthtalk.utils.FriendHttpUtil;
import com.yksj.healthtalk.utils.FriendUtil;
import com.yksj.healthtalk.utils.JsonParseUtils;
import com.yksj.healthtalk.utils.TimeUtil;
import com.yksj.healthtalk.utils.ToastUtil;
import com.yksj.healthtalk.utils.ViewFinder;
import com.yksj.healthtalk.utils.ViewUtils;

public class MyDoctorCommonServiceActivity extends BaseFragmentActivity
		implements OnClickListener, OnRefreshListener<ScrollView>,
		OnDilaogClickListener {
	public static final int REQUESTCODE = 1;
	private EditText mDescribeEt;// 医生提示
	private ServiceTypeView mServiceTypeView;
	private LinearLayout buttons;// 下面的按钮
	private String doctorId;
	private CustomerInfoEntity mCustomerInfoEntity;
	private TextView mServiceMoney;// 金额
	private TextView mServiceName;// 服务名称
	private String response;
	private PullToRefreshScrollView scrollView;
	private TickMesg mesg;
	private TextView mServiceStart;
	private TextView mServiceEnd;
	private WithdrawingRegistrationFragment fragment2;
	private int id;
	private int mClickBtnId;// 判断点击的是哪个id的对话框
	private ViewFinder mFinder;

	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.doctor_common_service);
		mFinder = new ViewFinder(this);
		initWidget();
		initData();
	}

	// 控件
	private void initWidget() {
		initTitle();
		((PullToRefreshScrollView) findViewById(R.id.pull_refresh_scrollview))
				.setLayoutInvisible();
		scrollView = (PullToRefreshScrollView) findViewById(R.id.pull_refresh_scrollview);
		scrollView.setOnRefreshListener(this);
		mDescribeEt = mFinder.find(R.id.describe);
		mServiceStart = mFinder.find(R.id.service_start);
		mServiceEnd = mFinder.find(R.id.service_end);
		mServiceMoney = mFinder.find(R.id.service_money);
		mServiceName = mFinder.find(R.id.service_name);
		mServiceTypeView = (ServiceTypeView) findViewById(R.id.service_type_view);
		buttons = (LinearLayout) findViewById(R.id.buttons_lin);

		titleTextV.setText("VIP服务");

		titleLeftBtn.setOnClickListener(this);

	}

	// 服务内容
	public void onClickServcieContent(View v) {
		Intent intent = new Intent(getApplicationContext(),
				DoctorServiceActivity.class);
		if (mesg != null) {
			intent.putExtra("ORIDERID", mesg.getORDER_ID());
		} else {
			return;
		}
		intent.putExtra("isbuy", true);
		startActivity(intent);
	}

	private void initData() {
		if (response == null) {
			Intent intent = getIntent();
			mCustomerInfoEntity = (CustomerInfoEntity) intent.getExtras().get(
					"mCustomerInfoEntity");
			response = intent.getExtras().getString("response");
			id = intent.getIntExtra("id", 0);
			doctorId = mCustomerInfoEntity.getId();
		}
		try {
			JSONObject object = JSON.parseObject(response);
			if (!TextUtils
					.isEmpty(object.getString("SERVICE_ITEM_DESC").trim()))
				mDescribeEt.setText(object.getString("SERVICE_ITEM_DESC"));
			mesg = (TickMesg) JSON.parseObject(object.toString(),
					TickMesg.class);
			// 所享受服务内容
			mFinder.setText(R.id.service_content1,
					object.getString("SERVICE_CONTENT"));
			if (id == 6) {
				initBottomButton(1);
				int code = Integer.valueOf(mCustomerInfoEntity
						.getServiceStatusCode());
				Button button = (Button) findViewById(BUTTON.delete.getId());//支付宝
				Button button1 = (Button) findViewById(BUTTON.wallet.getId());//钱包
				Button button2 = (Button) findViewById(10000);//银行卡
				if (code == 222 || code == 175 || code == 180) {// 申请退款
					button.setText("退款到支付宝");
					button.setBackgroundResource(R.drawable.login_out_btn_selector);
					button.setTextColor(getResources().getColorStateList(
							R.color.text_blue));
					button1.setText("存入钱包");
					button1.setBackgroundResource(R.drawable.login_button);
					button1.setTextColor(getResources().getColorStateList(
							R.color.text_green));
					button2.setText("退款到银行卡");
					button2.setBackgroundResource(R.drawable.login_out_btn_selector);
					button2.setTextColor(getResources().getColorStateList(
							R.color.text_blue));
					button.setVisibility(View.VISIBLE);
					button1.setVisibility(View.VISIBLE);
					button2.setVisibility(View.VISIBLE);
					button.setOnClickListener(this);
					button1.setOnClickListener(this);
					button2.setOnClickListener(this);
				} else {
					if(code==232){
						findViewById(R.id.message).setVisibility(View.VISIBLE);
						findViewById(R.id.message_content).setVisibility(View.VISIBLE);
						TextView tv=(TextView) findViewById(R.id.message_content);
						tv.setText("工作人员正在为您办理退款,请耐心等待,如有疑问,请咨询课务代表(010-51668809)");
					}
					button2.setVisibility(View.GONE);
					button.setVisibility(View.GONE);
					button1.setVisibility(View.GONE);
				}
			} else {
				initBottomButton(4);
			}
			mServiceTypeView.setVisibility(View.GONE);
			if (id == 5) {// 支付失败不显示截至时间
				mServiceStart = (TextView) findViewById(R.id.time);
				findViewById(R.id.start_end_time).setVisibility(View.INVISIBLE);
			} else {
				findViewById(R.id.start_end_time).setVisibility(View.VISIBLE);
				findViewById(R.id.service_content).setVisibility(View.VISIBLE);
				findViewById(R.id.pay_time).setVisibility(View.GONE);
			}
			if (mesg != null) {
				mServiceMoney.setText(mesg.getSERVICE_GOLD() + "元");
				mServiceName.setText(mesg.getSERVICE_TYPE_SUB());
				if (!TextUtils.isEmpty(mesg.getORDER_CREATE_TIME())) {
					mServiceStart.setText(TimeUtil.getFormatTime1(mesg
							.getORDER_CREATE_TIME()));
				} else {
					mServiceStart.setText("");
				}
				if (!TextUtils.isEmpty(mesg.getSERVICE_END())) {
					mServiceEnd.setText(TimeUtil.getFormatTime1(mesg
							.getSERVICE_END()));
				} else {
					mServiceEnd.setText("");
				}
			}
			if (!TextUtils.isEmpty(mCustomerInfoEntity.getServiceStatusCode())) {
				FriendUtil.isVisibleButtons(mCustomerInfoEntity, mesg, Integer
						.valueOf(mCustomerInfoEntity.getServiceStatusCode()),
						buttons, (TextView) findViewById(R.id.message_content),
						(TextView) findViewById(R.id.message), id);
			}

		} catch (Exception e) {
		}
	}

	// 初始化按钮
	private void initBottomButton(int j) {
		Button button;
		for (int k = 0; k < buttons.getChildCount(); k++) {
			buttons.getChildAt(k).setVisibility(View.VISIBLE);
		}
		for (int i = 0; i < buttons.getChildCount(); i++) {
			if (j == 1) {
				if (i == 0) {//
					
					button = (Button) buttons.getChildAt(0);
					button.setId(BUTTON.delete.getId());
					button.setBackgroundResource(R.drawable.login_out_btn_selector);
					button.setTextColor(getResources().getColorStateList(
							R.color.text_blue));
				} else if (i == 1) {
					button = (Button) buttons.getChildAt(1);
					button.setId(10000);
					button.setBackgroundResource(R.drawable.login_out_btn_selector);
					button.setTextColor(getResources().getColorStateList(
							R.color.text_blue));
				} else if (i == 2) {
					button = (Button) buttons.getChildAt(2);
					button.setId(BUTTON.wallet.getId());
					button.setBackgroundResource(R.drawable.login_button);
					button.setTextColor(getResources().getColorStateList(
							R.color.text_green));
				} else {
					buttons.getChildAt(i).setVisibility(View.GONE);
				}

			} else if (j == 2) {
				if (i == buttons.getChildCount() - 2
						|| i == buttons.getChildCount() - 1) {
					button = (Button) buttons.getChildAt(buttons
							.getChildCount() - 2);
					button.setText("删除");
					button.setTextColor(getResources().getColor(
							R.color.text_blue));
					button.setBackgroundResource(R.drawable.login_out_btn_selector);
					button.setId(BUTTON.delete.getId());
					button.setOnClickListener(this);
					button = (Button) buttons.getChildAt(buttons
							.getChildCount() - 1);
					button.setText("支付");
					button.setTextColor(getResources().getColor(
							R.color.text_green));
					button.setBackgroundResource(R.drawable.login_button);
					button.setId(BUTTON.pay.getId());
					button.setOnClickListener(this);
				} else {
					buttons.getChildAt(i).setVisibility(View.GONE);
				}
			} else if (j == 4) {
				switch (i) {
				case 0:
					button = (Button) buttons.getChildAt(0);
					button.setText("看医生");
					button.setId(BUTTON.pay.getId());
					button.setOnClickListener(this);
					break;
				case 1:
					button = (Button) buttons.getChildAt(1);
					button.setText("请求延时");
					button.setId(BUTTON.Time.getId());
					button.setOnClickListener(this);
					break;
				case 2:
					button = (Button) buttons.getChildAt(2);
					button.setText("提醒医生");
					button.setId(BUTTON.alert.getId());
					button.setOnClickListener(this);
					break;
				case 3:
					button = (Button) buttons.getChildAt(3);
					button.setText("退订服务");
					button.setId(BUTTON.unsubscribe.getId());
					button.setOnClickListener(this);
					break;
				default:
					break;
				}
			} else {
				buttons.getChildAt(i).setVisibility(View.GONE);
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_back:
			onBackPressed();
			break;
		default:
			if (v.getId() == BUTTON.pay.getId()) {
				FriendHttpUtil.onItemClick(MyDoctorCommonServiceActivity.this,
						mCustomerInfoEntity);
			} else if (v.getId() == BUTTON.Time.getId()) {
				mClickBtnId = BUTTON.Time.getId();
				DoubleBtnFragmentDialog.showDefault(
						getSupportFragmentManager(),
						getString(R.string.customer_time_message), "取消", "确定",
						this);
			} else if (v.getId() == BUTTON.alert.getId()) {
				HttpRestClient.doHttpRemindDoctor(
						SmartFoxClient.getLoginUserId(), doctorId,
						mesg.getORDER_ID(), new AsyncHander(v.getId()));
			} else if (v.getId() == BUTTON.unsubscribe.getId()) {
				HttpRestClient.doHttpServiceSetServlet(
						SmartFoxClient.getLoginUserId(), doctorId,
						mesg.getORDER_ID(), new AsyncHander(v.getId()));
			} else if (v.getId() == BUTTON.delete.getId()) {// 申请退款
				if (!TextUtils.isEmpty(mCustomerInfoEntity
						.getServiceStatusCode())) {
					int code = Integer.valueOf(mCustomerInfoEntity
							.getServiceStatusCode());
					if (code == 175 || code == 180 || code == 222) {
						HttpRestClient.doHttpRefundOrWatch(SmartFoxClient
								.getLoginUserId(), mCustomerInfoEntity.getId(),
								mCustomerInfoEntity.getOrderId(), "Refund",
								new AsyncHander(id, "Refund",
										mCustomerInfoEntity.getOrderId(),
										mCustomerInfoEntity.getId()));
					}
				}
			} else if (v.getId() == BUTTON.wallet.getId()) {
				mClickBtnId = BUTTON.wallet.getId();
				DoubleBtnFragmentDialog.showDefault(
						getSupportFragmentManager(),
						"为了您的账户安全，存入钱包后请绑定手机并设置支付密码。您确定将服务金额（"
								+ (mesg.getSERVICE_PRICE() != null ? mesg
										.getSERVICE_PRICE() : mesg
										.getSERVICE_GOLD()) + "元）存入钱包吗？", "放弃",	"确定", this);
			} else if (v.getId() == 10000) {
				mClickBtnId = 10000;
				if (!TextUtils.isEmpty(mCustomerInfoEntity
						.getServiceStatusCode())) {
					int code = Integer.valueOf(mCustomerInfoEntity
							.getServiceStatusCode());
					if (code == 175 || code == 180 || code == 222) {
						HttpRestClient.doHttpRefundOrWatch(SmartFoxClient
								.getLoginUserId(), mCustomerInfoEntity.getId(),
								mCustomerInfoEntity.getOrderId(), "Refund410",
								new AsyncHander(id, "Refund",
										mCustomerInfoEntity.getOrderId(),
										mCustomerInfoEntity.getId()));
					}
				}
			}
			break;
		}
	}

	public enum BUTTON {
		pay(1), Time(2), alert(3), unsubscribe(4), delete(5), wallet(6);
		int id;

		BUTTON(int id) {
			this.id = id;
		}

		int getId() {
			return id;
		}
	}

	class AsyncHander extends AsyncHttpResponseHandler {

		private int ButtonId;
		private LodingFragmentDialog dialog;
		private String type;
		private String payid;
		private String doctorId;
		private int id;

		public AsyncHander(int id) {
			super(MyDoctorCommonServiceActivity.this);
			this.ButtonId = id;
		}

		public AsyncHander(int id, String type, String payid, String doctorId) {
			super(MyDoctorCommonServiceActivity.this);
			this.type = type;
			this.payid = payid;
			this.doctorId = doctorId;
			this.id = id;
		}

		@Override
		public void onSuccess(int statusCode, String content) {
			try {
				Object object = JSON.parse(content);
				if (object == null && ButtonId == BUTTON.delete.getId()) {// 删除订单
					ToastUtil.showShort(getApplicationContext(), "删除订单成功");
					finish();
				} else if (object == null && ButtonId == BUTTON.alert.getId()) {
					ToastUtil.showShort(getApplicationContext(),R.string.customer_alert_message);
					finish();
				} else if (object instanceof JSONObject) {
					JSONObject object2 = (JSONObject) object;
					if (object2.containsKey("error_message")) {
						SingleBtnFragmentDialog.showDefault(	getSupportFragmentManager(),	object2.getString("error_message"));
						return;
					} else if (id == 6 && ButtonId != BUTTON.wallet.getId()) {
						// 退款
						if (type.equalsIgnoreCase("Refund")) {
							if (mClickBtnId != 10000) {
								Intent intent = new Intent(getApplicationContext(),RefundActivity.class);
								Bundle bundle = new Bundle();
								bundle.putString("account",	object2.getString("PAY_ACCOUNT"));
								bundle.putString("payId", payid);
								bundle.putString("tel",object2.getString("TRANSFER_GETTELE"));
								bundle.putString("customerId", doctorId);
								bundle.putBoolean("bankcard", false);
								intent.putExtras(bundle);
								startActivity(intent);
								finish();
							}
							if(mClickBtnId == 10000){//退款到银行卡
								Intent intent = new Intent(getApplicationContext(),RefundActivity.class);
								Bundle bundle = new Bundle();
								bundle.putString("account",	object2.getString("TRANSFER_CODE"));
								bundle.putString("openbank",	object2.getString("TRANSFER_NAME"));
								bundle.putString("tel",object2.getString("TRANSFER_GETTELE"));
								bundle.putString("customerId", doctorId);
								bundle.putString("payId", payid);
								bundle.putBoolean("bankcard", true);
								intent.putExtras(bundle);
								startActivity(intent);
								finish();
							}
							
						} else if (type.equalsIgnoreCase("ViewRefunds")) {
							// {"PAY_ACCOUNT":"1","ORDER_UPDATE_TIME":"20130923155508","PAY_ID":"130920007144600","TRANSFER_GETTELE":"ss","PAY_OK_TIME":null,"SERVICE_END":null,"TRANSACTION_ID":"2013092055619153","NOTE":null,"SERVICE_FEEDBACK":null,"SERVICE_GOLD":1,"SERVICE_STATUS":232,"ENJOY_CUSTOMER_ID":133585,"ORDER_ID":1222,"SERVICE_ALREADY":"N","FEEDBACK_TIME":null,"ORDER_CLASS_ID":10,"PAY_TYPE_ID":null,"SERVICE_CUSTOMER_ID":132871,"ORDER_CREATE_TIME":"20130920144627","MERCHANT_ID":null,"SERVICE_START":null}
							Intent intent = new Intent(getApplicationContext(),
									ToSeeRefundActivity.class);
							Bundle bundle = new Bundle();
							if (object2.containsKey("PAY_ACCOUNT")) {
								bundle.putString("account",
										object2.getString("PAY_ACCOUNT"));
								bundle.putString("tel",
										object2.getString("TRANSFER_GETTELE"));
							}
							intent.putExtras(bundle);
							startActivity(intent);
						}
																												
					} else if (object2.containsKey("LING")	&& ButtonId == BUTTON.pay.getId()) {// 价格为0 跳转到 聊天界面
						FriendHttpUtil.onItemClick(MyDoctorCommonServiceActivity.this,mCustomerInfoEntity);
					} else if (ButtonId == BUTTON.unsubscribe.getId()) {// 退订服务
						if (object2.containsKey("PAY_ACCOUNT")) {
							// 绑定的手机号码
							String payAccount = object2	.getString("PAY_ACCOUNT");
							String tel = object2.getString("TRANSFER_GETTELE");
							FragmentTransaction transaction = getSupportFragmentManager()	.beginTransaction();
							fragment2 = (WithdrawingRegistrationFragment) WithdrawingRegistrationFragment.getInstance(mCustomerInfoEntity,	payAccount, tel, mesg.getORDER_ID());
							transaction.add(android.R.id.content, fragment2);
							transaction.addToBackStack(null);
							transaction.commitAllowingStateLoss();
						}
					} else if (ButtonId == BUTTON.Time.getId()) {
						ToastUtil.showShort(getApplicationContext(),"请求延时成功...");
						finish();
					} else if (ButtonId == BUTTON.alert.getId()) {
						SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(),object2.getString("message"));
					} else if (ButtonId == BUTTON.wallet.getId()) {
						finish();
					}
				
				}
			} catch (Exception e) {
			}
			super.onSuccess(statusCode, content);
		}

	}

	@Override
	public void onBackPressed() {
		if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
			getSupportFragmentManager().popBackStackImmediate();
			refresh();
		} else {
			finish();
		}
	}

	@Override
	public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
		// refresh();
		scrollView.onRefreshComplete();
	}

	/**
	 * 重新请求界面
	 */
	private void refresh() {
		HttpRestClient.doHttpMyDoctorOrderDetail(
				SmartFoxClient.getLoginUserId(), mesg.getORDER_ID(),
				mCustomerInfoEntity.getId(),
				new JsonsfHttpResponseHandler(this) {

					@Override
					public void onStart() {
						scrollView.setLayoutVisible();
						scrollView.setRefreshing();
						super.onStart();
					}

					@Override
					public void onFinish() {
						scrollView.setLayoutInvisible();
						scrollView.onRefreshComplete();
						super.onFinish();
					}

					@Override
					public void onSuccess(int statusCode, JSONObject res) {
						if (JsonParseUtils.filterErrorMessage(response) == null) {
							response = res.toString();
							initData();
						} else {
							ToastUtil.showShort(getApplicationContext(),JsonParseUtils.filterErrorMessage(res));
						}
						super.onSuccess(statusCode, res);
					}
				});
	}

	@Override
	public void onDismiss(DialogFragment fragment) {
	}

	@Override
	public void onClick(DialogFragment fragment, View v) {
		if (mClickBtnId == BUTTON.Time.getId()) {// 延时
			HttpRestClient.doHttpDelayed(SmartFoxClient.getLoginUserId(),
					doctorId, mesg.getORDER_ID(),
					new AsyncHander(BUTTON.Time.getId()));
		} else {
			if (mesg != null) {// 存入钱包
				HttpRestClient.doHttpRefundWallet(mesg.getORDER_ID(),	new AsyncHander(BUTTON.wallet.getId()));
			}
		}

	}

}
